#include <stdio.h>
#include "status.h"
#include "network.h"
#include "clock.h"

static const char *
net_devices[] = {
    "/sys/class/net/wlp1s0/",
    "/sys/class/net/enp2s0/",
    NULL,
};

long
read_down_bytes(Arg * arg)
{
    long sum = 0.0;
    long temp = 0.0;
    FILE * file;

    for (int i = 0; *(net_devices + i); i++) {
        char path[size(*(net_devices + i)) + size("statistics/rx_bytes") + 1];

        sprintf(path, "%s%s", *(net_devices + i), "statistics/rx_bytes");
        file = fopen(path, "r");
        fscanf(file, "%ld", &temp);
        sum += temp;

        fclose(file);
    }

    return sum;
}

long
read_up_bytes(Arg * arg)
{
    long sum = 0.0;
    long temp = 0.0;
    FILE * file;

    for (int i = 0; *(net_devices + i); i++) {
        char path[size(*(net_devices + i)) + size("statistics/tx_bytes") + 1];

        sprintf(path, "%s%s", *(net_devices + i), "statistics/tx_bytes");
        file = fopen(path, "r");
        fscanf(file, "%ld", &temp);
        sum += temp;

        fclose(file);
    }

    return sum;
}

long double
get_down_kbps(Arg * arg)
{
    long new_bytes = read_down_bytes(NULL);
    long double new_time = get_time(NULL);
    return ((long double) new_bytes - arg->last_down_bytes) /
           1024.0 / (new_time - arg->last_time);
}

long double
get_up_kbps(Arg * arg)
{
    long new_bytes = read_up_bytes(NULL);
    long double new_time = get_time(NULL);
    return ((long double) new_bytes - arg->last_up_bytes) /
           1024.0 / (new_time - arg->last_time);
}
